package com.itheima.aspect;

import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.*;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;


/**
 * @author: zhengsuyang
 * @Desc:
 * @create: 2025-09-14 20:32
 **/
@Component
@Aspect
@Slf4j
public class RecodeLoginAspect {
    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("execution(* com.itheima.controller.LoginController.login(..))")
    public Object recordLogin(ProceedingJoinPoint joinPoint) throws Throwable {
        log.info("记录登录日志");
        // 1.记录方法执行开始时间
        long begin = System.currentTimeMillis();
        Object proceed = null;
        // 获取参数
        Object[] args = joinPoint.getArgs();
        // 分别获取里面的参数
        EmpDto empDto = (EmpDto) args[0];
        String username = empDto.getUsername();
        String password = empDto.getPassword();
        log.info("用户名:{}", username);
        log.info("密码:{}", password);
        // 获取返回值
        Result result = null;
        EmpLoginLog empLoginLog = new EmpLoginLog();
        // 设置公共字段
        empLoginLog.setUsername(username);
        empLoginLog.setPassword(password);
        empLoginLog.setLoginTime(LocalDateTime.now());
        try {
            proceed = joinPoint.proceed();
            long end = System.currentTimeMillis();
            result = (Result) proceed;
            empLoginLog.setCostTime(end - begin);
            // 根据结果设置成功或失败状态
            if (result.getCode() == 1) {
                log.info("登录成功");
                // 获取token令牌
                LoginInfo loginInfo = (LoginInfo) result.getData();
                String token = loginInfo.getToken();
                empLoginLog.setIsSuccess((short)1);
                empLoginLog.setJwt(token);
            } else {
                log.info("登录失败");
                empLoginLog.setIsSuccess((short)0);
            }

        } catch (Throwable throwable) {
            // 处理执行异常的情况
            empLoginLog.setIsSuccess((short)0);
            long end = System.currentTimeMillis();
            empLoginLog.setCostTime(end - begin);
            log.error("登录过程异常", throwable);
            throw throwable; // 重新抛出异常
        }
        finally{
            // 插入日志
            operateLogMapper.insertEmpLog(empLoginLog);
        }
        return proceed;
    }
}
